package simulator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Simulator{
	
	public static class Configuration{
		private Map<String,String> fields = new HashMap<String, String>();
		private String name;
		private File directory;
		
		public Configuration(String directory, String name) {
			this.directory = new File(directory);
			this.name = name;
			fields.put("A_#ROBOTS","1");
			fields.put("WORLD_PATH",".\\worlds");
			fields.put("WORLD_FILE","inner2.world");
			fields.put("TEST_SAME_START_POSITION","1");
			fields.put("UPDATE_DELAY","100");
			fields.put("VERBOSE_LEVEL","3");
			fields.put("SCALE","0.4");
			fields.put("SERVER_PORT","1033");
			fields.put("ENERGY_DECREASE","0.001");
			fields.put("SENSOR_NOISE","0");
			fields.put("NOISE_PERCENTAGE","5");
			fields.put("MOVE_OBSTACLES","0");
		}

		public String getName() {
			return name;
		}

		public File getDirectory() {
			return directory;
		}
		
		public void setField(String key, String value){
			fields.put(key, value);
		}
		
		public String getField(String key){
			return fields.get(key);
		}
		
		public void write(){
			try {
				BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(directory.getAbsolutePath()+"/"+name));
				bufferedWriter.write("###############################################");
				bufferedWriter.newLine();
				bufferedWriter.write("# This file was generated automatically.      #");
				bufferedWriter.newLine();
				bufferedWriter.write("# Therefore changing manually makes no sense. #");
				bufferedWriter.newLine();
				bufferedWriter.write("# Author: R.Lioutikov                         #");
				bufferedWriter.newLine();
				bufferedWriter.write("# Timestamp: "+new Date()+"     #");
				bufferedWriter.newLine();
				bufferedWriter.write("###############################################");
				bufferedWriter.newLine();
				bufferedWriter.newLine();
				
				for(Entry<String,String> entry : fields.entrySet()){
					bufferedWriter.write(entry.getKey()+"\t"+entry.getValue());
					bufferedWriter.newLine();
				}
				bufferedWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
		
	}
	
	public static Process start(Configuration config) {
		try {
			config.write();
			ProcessBuilder processBuilder = new ProcessBuilder(config.getDirectory().getAbsolutePath()+"/YAKS.exe",config.getName());
			processBuilder.directory(config.getDirectory());
			Process process = processBuilder.start();
			new Thread(new Printer("Simulator",process.getErrorStream(),System.err)).start();
			new Thread(new Printer("Simulator",process.getInputStream(),System.out)).start();
			return process;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}	
	
}
